import {useState, useEffect} from 'react';
import {message} from 'antd';
import {TIME_DURATION, CORE_PAGE_ID} from '~/utils/const';
import {getAllPreference} from '~/service/performance';

import {generateLatestWeek, calcDateRangeStr, pathTransfer} from '../utils';
import {filterPathByApplication} from '../pathUtils';

export default () => {
    // 设置日期相关状态
    const [dateRange, setDateRange] = useState(generateLatestWeek());
    const [duration, setDuration] = useState(TIME_DURATION.ONE_DAY);
    // 设置应用状态
    const [application, setApplication] = useState('all');
    // all paths
    const [allPaths, setAllPaths] = useState([]);
    // 经过过滤后的path, 主要用于数据下载
    const [filterPaths, setFilterPaths] = useState([]);
    // 设置经过过滤和数据结构转换后的path
    const [formatPaths, setFormatPaths] = useState(null);

    const setDateRangeAndDuration = ({dateRange, duration}) => {
        if (dateRange) {
            setDateRange(dateRange);
        }
        if (duration) {
            setDuration(duration);
        }
    };

    // fetch all paths once
    useEffect(() => {
        const param = {
            pageId: CORE_PAGE_ID
        };
        getAllPreference(param).then(res => {
            if (res.code === 0) {
                setAllPaths(res.data.fullPreferences);
            }
            else {
                message.error(res.msg);
            }
        });
    }, []);

    // update lists
    useEffect(() => {
        const filterPaths = filterPathByApplication(allPaths, application);
        setFilterPaths(filterPaths);
        setFormatPaths(pathTransfer(filterPaths));
    }, [application, allPaths]);

    return [{dateRange, duration, application, formatPaths, filterPaths}, setApplication, setDateRangeAndDuration];

};
